/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets.patient.medicationtask;

import be.ugent.medirem.logic.MeasurementRemote;
import be.ugent.medirem.logic.MedicationRemote;
import be.ugent.medirem.logic.PatientRemote;
import be.ugent.medirem.persistence.entity.details.MeasurementDetails;
import be.ugent.medirem.persistence.entity.details.MedicationDetails;
import entities.DoseCheckerBeanService;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.WebServiceRef;

/**
 *
 * @author Roelie
 */
public class VariableDosageServlet extends HttpServlet {

    @WebServiceRef(wsdlLocation = "WEB-INF/wsdl/chaos169.test.atlantis.ugent.be_8080/DoseCheckerBeanService/DoseCheckerBean.wsdl")
    private DoseCheckerBeanService service;
    @EJB
    private MeasurementRemote measurementBean;
    @EJB
    private PatientRemote patientBean;
    @EJB
    private MedicationRemote medicationBean;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String username = request.getUserPrincipal().getName();
        Long pId = patientBean.getPatientId(username);
        boolean validate = true;

        try {
            Long alreadyTakenMeasurementId = null;
            if (request.getParameter("measurementId") != null) {  // -1 is first option "---"
                alreadyTakenMeasurementId = Long.parseLong(request.getParameter("measurementId"));
            }
            Long medicationId = Long.parseLong(request.getParameter("mId"));
            Long taskId = Long.parseLong(request.getParameter("taskId"));
            double value = 0;
            if (!request.getParameter("measurementValue").isEmpty()) {
                value = Double.parseDouble(request.getParameter("measurementValue"));
            }

            if (value == 0 && alreadyTakenMeasurementId == -1) {
                // The input was invalid
                validate = false;
            } else {
                // Valid input
                String typeName = "";
                String medicationName = "";
                double stdDose = 0;

                MedicationDetails mediDetails = medicationBean.getMedicationDetails(medicationId);
                stdDose = mediDetails.getStdDose();
                medicationName = mediDetails.getName();

                if (alreadyTakenMeasurementId != null && alreadyTakenMeasurementId != -1) {
                    MeasurementDetails mDetails = measurementBean.getMeasurementDetails(alreadyTakenMeasurementId);
                    value = mDetails.getMeasurementValue();
                    typeName = mDetails.getType();
                } else {
                    typeName = mediDetails.getMeasurementType();
                }



                try { // Call Web Service Operation
                    entities.DoseCheckerBean port = service.getDoseCheckerBeanPort();

                    double result = port.getVariableDoseForName(typeName, value, medicationName, stdDose);

                    request.setAttribute("dose", result);

                } catch (Exception ex) {
                    validate = false;
                }

                request.setAttribute("task", taskId);
                request.setAttribute("medication", medicationName);
                request.setAttribute("unit", mediDetails.getUnit());

                if (validate) {
                    request.getRequestDispatcher("/patient/medicationtask/takevariable.jsp").forward(request, response);
                }
            }

        } catch (Exception ex) {
            validate = false;
            Logger.getLogger(VariableDosageServlet.class.getName()).log(Level.SEVERE, null, ex);

        }

        if (!validate) {
            request.getSession().setAttribute("flash", "An error has occured when trying to call the webservice, please try again");
            request.getRequestDispatcher("/patient/medicationtask/takevariable.jsp").forward(request, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException,
            IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException,
            IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
